const MongoClient = require('mongodb').MongoClient;
const connectStr = 'mongodb://localhost:27017';

const mysql = {
  insert (collectionName, insertData) {
    return new Promise((resolve, reject) => {
      MongoClient.connect(connectStr, (err, client) => {
        if(err) throw err;
        const db = client.db('zz1807');
        const collection = db.collection(collectionName);
        collection.insert(insertData, (err) => {
          if(err){
            reject(err)
            client.close()
          } else {
            resolve()
            client.close()
          }
        })
      })
    })
  },
  remove(collectionName, deleteData) {
    return new Promise((resolve, reject) => {
      MongoClient.connect(connectStr, (err, client) => {
        if(err) throw err;
        const db = client.db("zz1807")
        const collection = db.collection(collectionName);
        collection.remove(deleteData, (err) => {
          if(err){
            reject(err);
            client.close();
          } else {
            resolve()
            client.close()
          }
        })
      })
    })
  },
  updateOne (collectionName, whereData, updateData) {
    return new Promise((resolve, reject) => {
      MongoClient.connect(connectStr, (err,cliect) => {
        if(err) throw err;
        const db = cliect.db('zz1807');
        const collection = db.collection(collectionName);
        collection.updateOne(whereData, updateData, (err) => {
          if(err){
            reject(err)
            cliect.close()
          } else {
            resolve()
            cliect.close()
          }
        })
      })
    })
  },
  find (collectionName, whereData, showData) {
    return new Promise((resolve, reject) => {
      MongoClient.connect(connectStr, (err, client) => {
        if (err) throw err;
        const db = client.db('zz1807');
        const collection = db.collection(collectionName);
        collection.find(whereData, showData).toArray((err, data) => {
          if (err) {
            reject(err);
            client.close();
            } else {
            resolve(data);
            client.close();
           }
         })
       })
      })
   }
  }
  
  
  
  

module.exports = mysql;